import { useEffect, useState } from "react";

function useMarkdownTypingEffect(markdown: string) {
  const [htmlContent, setHtmlContent] = useState("");
  const [currentIndex, setCurrentIndex] = useState(0);
  const [markdownQueue, setMarkdownQueue] = useState<string[]>([]);
  const [isTyping, setIsTyping] = useState(false);

  useEffect(() => {
    if (!isTyping && markdownQueue.length > 0) {
      setMarkdownQueue((prev) => prev.slice(1));
      setCurrentIndex(0);
      setHtmlContent("");
      setIsTyping(true);
    }
  }, [isTyping, markdownQueue]);

  useEffect(() => {
    if (currentIndex < markdown.length) {
      const timer = setTimeout(() => {
        setCurrentIndex((prev) => prev + 1);
        setHtmlContent(markdown.slice(0, currentIndex + 1));
      }, 10);
      return () => clearTimeout(timer);
    } else {
      setIsTyping(false);
    }
  }, [currentIndex, markdown]);

  useEffect(() => {
    if (markdown) {
      setMarkdownQueue((prev) => [...prev, markdown]);
    }
  }, [markdown]);

  return htmlContent;
}

export default useMarkdownTypingEffect;
